import { createStore } from "vuex";
import { login, getUserInfo } from "@/api/user.js"
import { getWFLocaleSchools } from "@/api/mission.js"
import { phoneHid } from "@/utils/base"
import env from "@/env"
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

const store = createStore({
  state: {
		token: null,
		userInfo: {},
		query: {}, // app跳转页面缓存参数
		refresh_dashboard: true,
		WFLocaleSchools: [],
		osName: "",
		
		tempRect: {}
	},
	mutations: {
		SET_TOKEN: (state, payload) => {
			state.token = payload.data
		},
		CLEAR_TOKEN: (state) => {
			state.token = null
		},
		SET_USERINFO: (state, payload) => {
			state.userInfo = payload.data
		},
		CLEAR_USERINFO: (state) => {
			state.userInfo = {}
		},
		SET_QUERY: (state, payload) => {
			state.query = payload.data
			// console.log("设置完成", state.query)
		},
		CLEAR_QUERY: (state) => {
			state.query = {}
		},
		SET_REFRESH_DASHBOARD: (state, payload) => {
			state.refresh_dashboard = payload.data
		},
		SET_WFLSCHOOLS: (state, payload) => {
			state.WFLocaleSchools = payload.data
		},
		CLEAR_WFLSCHOOLS: (state) => {
			state.WFLocaleSchools = []
		},
		SET_OS_NAME: (state, payload) => {
			state.osName = payload.data
		},
		SET_TEMP_RECT: (state, payload) => {
			state.tempRect = payload.data
		}
	},
	getters: {
		token: state => state.token,
		userInfo: state => state.userInfo,
		query: state => state.query,
		osName: state => state.osName,
		tempRect: state => state.tempRect,
	},
	
	actions: {
		/* 账号密码 */
		passwordLogin({ commit }, data) {
			return new Promise((resolve, reject) => {
				login(data)
					.then((response) => {
						// 本地缓存用户登陆状态
						const { token } = response
						uni.setStorageSync("token", token)
						commit("SET_TOKEN", { data: token })
						getUserInfo()
							.then((res) => {
								console.log("userInfo", res)
								const role = res.roles.includes("superintendent") ? 1 : 2
								const { user: { avatar, nickName, superintendentId, userId, phonenumber, roleName } } = res
								const data = {
									avatar,
									role,
									permissions: res.roles,
									id: userId,
									username: nickName,
									phone: phoneHid(phonenumber),
									position: roleName,
									school: ""
								}
								uni.setStorageSync("userInfo", data)
								commit("SET_USERINFO", { data })
								resolve(true)
							})
							.catch((err) => {
								reject(err)
							})
							
						getWFLocaleSchools()
							.then((res) => {
								commit("SET_WFLSCHOOLS", { data: res })
							})
					})
					.catch(error => {
						console.log(error)
						reject(error)
					})
			})
		},
		
		/**
		 * 授权登录|免登
		 */
		fastlogin({ commit }) {
			return new Promise((resolve, reject) => {
				
				dd.getAuthCode({}).then((res) => {
					if (res.code) {
						uni.request({
							url: env.AUTH_URL + "/user/login",
							method: "POST",
							timeout: 15000,
							data: { auth_code: res.code },
							success(res) {
								if (res.statusCode === 200) {
									uni.setStorageSync("token", res.data.token)
									commit("SET_TOKEN", { data: res.data.token })
									getUserInfo()
										.then((res) => {
											console.log("userInfo", res)
											const role = res.roles.includes("superintendent") ? 1 : 2
											const { user: { avatar, nickName, superintendentId, userId, phonenumber, roleName } } = res
											const data = {
												avatar,
												role,
												permissions: res.roles,
												id: userId,
												username: nickName,
												phone: phoneHid(phonenumber),
												position: roleName,
												school: ""
											}
											uni.setStorageSync("userInfo", data)
											commit("SET_USERINFO", { data })
											resolve("success")
										})
										.catch((err) => {
											reject(err)
										})
									
									getWFLocaleSchools()
										.then((res) => {
											commit("SET_WFLSCHOOLS", { data: res })
										})
								} else {
									// console.log("自动登陆请求结果失败", res)
									uni.showToast({
										title: "自动登陆失败，请尝试账号密码登录40001",
										icon: 'none'
									})
									reject("自动登陆失败，请尝试账号密码登录40001")
								}
							},
							fail: function(err) {
								uni.showToast({
									title: "自动登陆失败，请尝试账号密码登录40002",
									icon: 'none'
								})
								reject("自动登陆失败，请尝试账号密码登录40002")
							}
						})
					} else {
						uni.showToast({
							title: "获取鉴权码失败40003",
							icon: 'none'
						})
						reject()
					}
				}).catch((err) => {
					console.log(err)
					uni.showToast({
						title: "无法获取鉴权码",
						icon: 'none'
					})
					reject()
				})
			})
		},
		
		/**
		 * 登出
		 */
		logout({ commit }) {
			return new Promise((resolve) => {
				commit("CLEAR_TOKEN")
				commit("CLEAR_USERINFO")
				commit("CLEAR_WFLSCHOOLS")
				uni.removeStorageSync("token")
				uni.removeStorageSync("userInfo")
				uni.removeStorageSync("mission_cache_data")
				resolve(true)
			})
		},
		
		getQuery({ state, commit }) {
			return new Promise((resolve) => {
				const q = { ...state.query }
				commit("CLEAR_QUERY")
				resolve(q)
			})
		},
		
		
	}
	
	
})
export default store;